package com.plian.system.service.yth.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.plian.Tools.CollectionUtil;
import com.plian.system.entity.dp.AnnualWorkReport;
import com.plian.system.entity.yth.stafffiles.WorkReport;
import com.plian.system.mapper.yth.staffFiles.WorkReportMapper;
import com.plian.system.service.yth.IWorkReportService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.ZoneId;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Optional;

@Slf4j
@Service
public class WorkReportServiceImpl extends ServiceImpl<WorkReportMapper, WorkReport> implements IWorkReportService {
    private final String YTH_DATASOURCE_TYPE = "3";
    @Transactional(rollbackFor = Exception.class)
//    @DS("slave_1")
    @Override
    public List<AnnualWorkReport> getAllProject(Date startTime, Date endTime) {
        List<AnnualWorkReport> annualWorkReports = new ArrayList<>();

        List<WorkReport> workReports = list(new LambdaQueryWrapper<WorkReport>()
                .gt(Optional.ofNullable(startTime).isPresent(),WorkReport::getCreateTime,startTime)
                .le(Optional.ofNullable(endTime).isPresent(),WorkReport::getCreateTime,endTime)
        );
        if (CollectionUtil.isNotEmpty(workReports)){
            annualWorkReports = conversion(workReports);
        }
        return annualWorkReports;
    }
    private List<AnnualWorkReport> conversion(List<WorkReport> workReports){
        List<AnnualWorkReport> annualWorkReports= new ArrayList<>();
        ZoneId zone = ZoneId.systemDefault();
        for (WorkReport workReport:workReports){
            AnnualWorkReport annualWorkReport = new AnnualWorkReport();
            annualWorkReport.setCode(workReport.getInvoiceCode());
            annualWorkReport.setReportCompanyId(String.valueOf(workReport.getReportOrgId()));
            Optional.ofNullable(workReport.getReportTime()).ifPresent( m ->{
                annualWorkReport.setReportTime(Date.from(m.atStartOfDay().atZone(zone).toInstant()));
            });
            annualWorkReport.setDataSource(YTH_DATASOURCE_TYPE);
            annualWorkReport.setDataSourceId(workReport.getId().toString());
            annualWorkReport.setAttachIds(workReport.getFileIds());
            annualWorkReport.setCreateCompanyId(workReport.getCreateDept().toString());
            annualWorkReport.setCreateUser(workReport.getCreateUser().toString());
            annualWorkReports.add(annualWorkReport);
        }
        return annualWorkReports;
    }
}
